package com.example.javamaday.leetcode;

import com.example.javamaday.leetcode.base.ListNode;

// 分割链表
public class LeetCodeTest0086 {

    public static void main(String[] args) {

    }

    // 给你一个链表的头节点 head 和一个特定值 x ，请你对链表进行分隔，使得所有 小于 x 的节点都
    // 出现在 大于或等于 x 的节点之前。你应当 保留 两个分区中每个节点的初始相对位置。
    public ListNode partition(ListNode head, int x) {
        ListNode dumpy = new ListNode(Integer.MIN_VALUE);
        ListNode pre = dumpy;
        ListNode current = head;

        ListNode right = null;
        ListNode rightCurrent = null;

        while (current != null) {
            if (current.val < x) {
                ListNode currentNext = current.next;
                current.next = null;
                pre.next = current;
                pre = pre.next;
                current = currentNext;
            } else {
                if (right == null) {
                    ListNode currentNext = current.next;
                    current.next = null;
                    right = current;
                    rightCurrent = right;
                    current = currentNext;
                } else {
                    ListNode currentNext = current.next;
                    current.next = null;
                    rightCurrent.next = current;
                    rightCurrent = rightCurrent.next;
                    current = currentNext;
                }
            }
        }
        pre.next = right;
        return dumpy.next;
    }

}
